const express = require('express')
const Router = express.Router()
const mongoose = require('mongoose')
const User = mongoose.model('User')
const Chat = mongoose.model('Chat')
const utils = require('utility')

// 过滤密码
const _filter = {pwd: 0, __v: 0}

// 获取用户列表
Router.get('/user/list', function (req, res) {
  let type = req.query.type
  let query = {}
  if (type) {
    query.type = type
  }
  User.find(query, _filter,function (err, doc) {
    if (err) {
      return res.json({code: 1})
    }
    res.json({code: 0, data: doc})
  })
})
// 获取 msglist 同时将用户信息给到
Router.get('/user/getmsglist', function (req, res) {
  let { userid } = req.cookies
  if (!userid) {
    return res.json({code: 1, msg: '未登录'})
  }
  // Chat.find({'$or': [{from: userid}, {to: userid}]})
  //   .populate('User', '_id name avatar')
  //   .exec(function (err, doc) {
  //     if (err) {
  //       return res.json({code: 1, msg: '服务端错误'})
  //     }
  //     return res.json({code: 0, msgs: doc})
  //   })
  User.find({}, function (err, userdoc) {
    let users = {}
    userdoc.forEach(v => {
      users[v._id] = {name: v.user, avatar: v.avatar}
    })
    Chat.find({'$or': [{from: userid}, {to: userid}]}, function (err, doc) {
      if (err) {
        return res.json({code: 1, msg: '服务端错误'})
      }
      return res.json({code: 0, msgs: doc, users: users})
    })
  })
})
// 获取与某一个人的聊天记录
// Router.get('/user/getmsg/:chatuserid', function (req, res) {
//   let { userid } = req.cookies
//   if (!userid) {
//     return res.json({code: 1, msg: '未登录'})
//   }
//   let chatuserid = req.params.chatuserid
//   console.log(chatuserid)
//   res.json(123)
// })
// 删除全部用户，测试使用
Router.get('/user/remove', function (req, res) {
  User.remove({}, function (err) {
    res.json('success remove all')
  })
})
// 注册
Router.post('/user/register', function (req, res) {
  let {user, pwd, type} = req.body
  User.findOne({user: user}, function (err, doc) {
    if (doc && doc._id) {
      return res.json({code: 1, msg: '用户名重复'})
    }
    let newUser = new User({user, type, pwd: md5Pwd(pwd)})
    newUser.save(function (e, d) {
      if (e) {
        return res.json({code: 1, msg: '创建用户失败'})
      }
      res.cookie('userid', d._id)
      return res.json({code: 0, data: {user, type, _id: d._id}})
    })
  })
})

// 用户信息更新
Router.post('/user/update', function (req, res) {
  let { userid } = req.cookies
  if (!userid) {
    return res.json({code: 1, msg: '未登录'})
  }
  let body = req.body
  User.findByIdAndUpdate(userid, body, function (err, doc) {
    if (err) {
      return res.json({code: 1, msg: '服务端错误'})
    }
    let data = Object.assign({}, {
      user: doc.user,
      type: doc.type
    }, body)
    return res.json({code: 0, data})
  })
})
// 标记信息已读
Router.post('/user/readmsg', function (req, res) {
  let { userid } = req.cookies
  if (!userid) {
    return res.json({code: 1, msg: '未登录'})
  }
  let { from } = req.body
  if (!from) {
    return res.json({code: 1, msg: '参数错误'})
  }
  Chat.update({from, to: userid, read: false}, {'$set': {read: true}}, {'multi': true},function (err, doc) {
    if (err) {
      return res.json({code: 1, msg: '服务端错误'})
    }
    // console.log('doc', doc) // { n: 14, nModified: 13, ok: 1 }
    return res.json({code: 0, num: doc.nModified})
  })
})
// 登录
Router.post('/user/login', function (req, res) {
  let {user, pwd} = req.body
  User.findOne({user, pwd: md5Pwd(pwd)}, _filter,function (err, doc) {
    if (err) {
      return res.json({code: 1, msg: '服务端错误'})
    }
    if (!doc) {
      return res.json({code: 1, msg: '用户名或密码错误'})
    }
    res.cookie('userid', doc._id)
    return res.json({code: 0, data: doc})
  })
})
// 根据 cookie 获取用户信息
Router.get('/user/info', function (req, res) {
  let { userid } = req.cookies
  if (!userid) {
    return res.json({code: 1})
  }
  User.findById(userid, _filter, function (err, doc) {
    if (err) {
      return res.json({code: 1, msg: '服务端错误'})
    }
    if (doc) {
      return res.json({code: 0, data: doc})
    }
    return res.json({code: 1})
  })
})

function md5Pwd(pwd) {
  let salt = 'newming1993'
  return utils.md5(utils.md5(pwd + salt))
}

module.exports = Router